package br.com.mtech.ctrlliberty.ejb.dao;

import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import br.com.mtech.ctrlliberty.clientjar.entity.CamposPesquisaVO;
import br.com.mtech.ctrlliberty.clientjar.entity.LigacaoVO;
import br.com.mtech.ctrlliberty.clientjar.entity.TelefoneVO;
import br.com.mtech.ctrlliberty.clientjar.util.Util;

/**
 * Session Bean implementation class LigacaoEJBDAO
 */
@Stateless
public class LigacaoEJBDAO implements LigacaoEJBDAOLocal {

	@PersistenceContext(unitName="CtrlLiberty")	
	EntityManager	entityManager;
	
	@Override
	public LigacaoVO recuperar(Long id) {
		return entityManager.find(LigacaoVO.class, id);
	}
	
	@Override
	public LigacaoVO inserir(LigacaoVO ligacao){
		entityManager.persist(ligacao);
		return ligacao;
	}
	
	@Override
	@SuppressWarnings("unchecked")
	public List<LigacaoVO> pesquisarLigacoes(TelefoneVO telefone, CamposPesquisaVO campos) {
		
		StringBuilder strQuery = new StringBuilder();
		
		strQuery.append("from LigacaoVO ligacao ");
		strQuery.append("where ligacao.telefone = :tel ");
		strQuery.append("and ligacao.dataInicioLigacao between :dataInicial and :dataFinal ");
		
		if(!Util.isEmpty(campos.getNumeroDDD())) {
			strQuery.append("and ligacao.numeroDDDRemoto = :numDDD ");
		}
		if(!Util.isEmpty(campos.getNumeroRemoto())) {
			strQuery.append("and ligacao.numeroRemoto = :numRemoto ");
		}
		if(campos.getTipoLigSms() != null) {
			strQuery.append("and ligacao.tipoLigacao = :tipoLigacao ");
		}
	
		Query query = entityManager.createQuery(strQuery.toString());
		query.setParameter("dataInicial", campos.getDataInicial());		
		query.setParameter("dataFinal", campos.getDataFinal());
		query.setParameter("tel", telefone);
		
		if(!Util.isEmpty(campos.getNumeroDDD())) {
			query.setParameter("numDDD", campos.getNumeroDDD());
		}
		if(!Util.isEmpty(campos.getNumeroRemoto())) {
			query.setParameter("numRemoto", Long.parseLong(campos.getNumeroRemoto()));
		}
		if(campos.getTipoLigSms() != null) {
			query.setParameter("tipoLigacao", campos.getTipoLigSms());
		}
		
		return query.getResultList();
	}

}
